home *** CD-ROM | disk | FTP | other *** search
- Path: news.sinet.slb.com!usenet
- From: "Vinh D. Nguyen" <vnguyen@sugar-land.anadrill.slb.com>
- Newsgroups: comp.lang.c++
- Subject: Re: "Deep" Destructor Query
- Date: Tue, 12 Mar 1996 08:22:17 -0600
- Organization: Schlumberger Anadrill
- Message-ID: <31458899.6A44@sugar-land.anadrill.slb.com>
- References: <826257180snz@pbutler.demon.co.uk>
- NNTP-Posting-Host: 163.185.118.40
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- Peter Hugh Butler wrote:
- > Object::~Object()
- > {
- > for (int i = 0; i < numshapes; i++)
- > shapes[i].~shape(); //"Deep" destructor, deletes underlying arrays.
- >
- > delete [] shapes; //delete the array of pointers
- > }
- >
- > The program causes a General Protection Fault (guess which OS I'm using and
- > win a cookie). It fails when it tries to delete the array of null pointers
- > pointed to by shape. It works when I leave the "delete [] shapes;" line out.
- >
- > Well, I have two questions:
- >
- > 1) If I simply "delete [] shapes" with no loop to delete the arrays underneath,
- > will the ~shape() destructor be automatically called, thus deleting the
- > shape objects correctly? I wouldn't think so, but it would be good to be
- > corrected.
-
- Just deleting the array of pointers will not destroy the objects pointed at. You
- must explicitly delete all the shape objects as you attempted to do in the code listing
- above. However, the correct way to do it is not to call the shape object's destructor
- explicitly but to use the delete operator as follows:
-
- Object::~Object()
- {
- for (int i = 0; i < numshapes; i++)
- delete shapes[i]; // delete the dynamically allocated shape objects
-
- delete [] shapes; //delete the array of pointers
- }
-
- The delete operator in turn will call the shape object's destructor before deleting
- the shape object.
-
- The problem with calling the destructor directly is that the object's content, in this
- case the point array, will be destroyed but not the object itself. To destroy the object,
- you'll have to use the delete operator. As a rule-of-thumb,
- you should never call the destructor yourself. Well, there are a few cases in which
- you can do that but that is extremely rare. In those cases, you can always write a
- cleanup helper function which is called both the destructor and where you want to
- clean up the object.
-
- --
- --------------------------------------------------------------------------
- * Vinh Nguyen vnguyen@slb.com *
- * Drilling Information Products - Senior Engineer *
- * Anadrill Schlumberger *
- * 200 Gillingham Ln. (713) 275-7524 (Office) *
- * Sugarland, TX 77478 (713) 275-8098 (FAX) *
- --------------------------------------------------------------------------
-